<?php
namespace App\Admin\Logic\Bj;

use App\Admin\Logic\BaseLogic;
use App\Logic\MachineLogic;
use App\Models\SwtBjCabinet;
use App\Models\SwtBjMachine;
use App\Services\BaoJianService;
use Illuminate\Support\Facades\DB;

class BjMachineLogic extends BaseLogic
{
    public static function asyncMachineToWarehouse($ids) {
        $machines = SwtBjMachine::whereIn('id', $ids)->get();

        if(empty($machines)) {
            self::$error = "设备不存在";
            return false;
        }

        $num = 0;

        foreach($machines as $machine) {
            $data = [
                'machine_no'        => $machine['machine_code'],
                'machine_name'      => $machine['machine_name'],
                'address'           => $machine['address'],
                'source_type'       => 2
            ];

            $res = MachineLogic::addMachine($data);

            if($res) {
                SwtBjMachine::where('id', $machine['id']) -> update(['machine_id' => $res]);
                $num ++;
            }
        }

        return $num;
    }

    public static function refreshMachineInfo($device_code)
    {
        $info = BaoJianService::machineStatus($device_code);

        DB::beginTransaction();
        try {

            $machine = SwtBjMachine::firstWhere('device_code', $device_code);

            $machine -> power_status = $info['powerStatus'];
            $machine -> online_status = $info['netStatus'];
            $machine -> sale_status = $info['saleStatus'];

            if($info['netStatus'] == 1) {
                $machine -> last_online_time = time();
            }

            $res = $machine -> save();

            if(!$res) {
                throw new \Exception('设备状态更新失败');
            }

            foreach($info['cabinetStatusList'] as $v) {
                $res = SwtBjCabinet::where('bj_machine_id', $machine->id)
                    -> where('cabinet_no', $v['cabinetNo'])
                    -> update(['lock_status'=>$v['lockStatus']]);

                if(!$res) {
                    throw new \Exception('柜门状态更新失败');
                }
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            DB::rollBack();
            return false;
        }
    }
}
